//
//  JOSplitViewDelegate.m
//  ViewSwapper
//
//  Created by Russell Newlands on 19/02/2012.
//  Copyright (c) 2012 Jominy Research. All rights reserved.
//

#import "JOSplitViewDelegate.h"

@implementation JOSplitViewDelegate

- (void)setMinimumLength:(CGFloat)minLength forViewAtIndex:(NSInteger)viewIndex
{
	if (!minViewLengthDict)
	{
		minViewLengthDict = [[NSMutableDictionary alloc] initWithCapacity:0];
	}
	
	[minViewLengthDict setObject:[NSNumber numberWithDouble:minLength] forKey:[NSNumber numberWithInteger:viewIndex]];
}

- (void)setCanResize:(BOOL)canResize forViewAtIndex:(NSInteger)viewIndex;
{
    if (!canResizeDict)
	{
		canResizeDict = [[NSMutableDictionary alloc] initWithCapacity:0];
	}
	
	[canResizeDict setObject:[NSNumber numberWithBool:canResize] forKey:[NSNumber numberWithInteger:viewIndex]];
}


/* NSSplitView Delegate methods */

- (BOOL)splitView:(NSSplitView *)splitView shouldAdjustSizeOfSubview:(NSView *)subview
{   
    NSArray *subviews = [splitView subviews];    
    NSUInteger indexOfSubview = [subviews indexOfObject:subview];
    return [[canResizeDict objectForKey:[NSNumber numberWithInteger:indexOfSubview]] boolValue];
}


- (CGFloat)splitView:(NSSplitView *)sender constrainMinCoordinate:(CGFloat)proposedMin ofSubviewAt:(NSInteger)offset
{
    NSView *subview = [[sender subviews] objectAtIndex:offset];
    NSRect subviewFrame = subview.frame;
    CGFloat frameOrigin;
    if ([sender isVertical])
    {
        frameOrigin = subviewFrame.origin.x;
    }
    else
    {
        frameOrigin = subviewFrame.origin.y;
    }
    
    CGFloat minimumSize = [[minViewLengthDict objectForKey:[NSNumber numberWithInteger:offset]] doubleValue];
    
    return frameOrigin + minimumSize;
}


- (CGFloat)splitView:(NSSplitView *)sender constrainMaxCoordinate:(CGFloat)proposedMax ofSubviewAt:(NSInteger)offset
{
	NSView *growingSubview = [[sender subviews] objectAtIndex:offset];
	NSView *shrinkingSubview = [[sender subviews] objectAtIndex:offset + 1];
	NSRect growingSubviewFrame = growingSubview.frame;
	NSRect shrinkingSubviewFrame = shrinkingSubview.frame;
	CGFloat shrinkingSize;
	CGFloat currentCoordinate;
	
    if ([sender isVertical])
	{
		currentCoordinate = growingSubviewFrame.origin.x + growingSubviewFrame.size.width;
		shrinkingSize = shrinkingSubviewFrame.size.width;
	}
	else
	{
		currentCoordinate = growingSubviewFrame.origin.y + growingSubviewFrame.size.height;
		shrinkingSize = shrinkingSubviewFrame.size.height;
	}
	
	CGFloat minimumSize = [[minViewLengthDict objectForKey:[NSNumber numberWithInteger:offset + 1]] doubleValue];
	
	return currentCoordinate + (shrinkingSize - minimumSize);
}


@end
